﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using AutoMail.Data;
using Quartz;
using Quartz.Impl;
using AutoMail.Service;
using AutoMail.Log;
using AutoMail.QuartzJobs.Interfaces;
using AutoMail.QuartzJobs;
using AutoMail.QuartzJobs.Jobs;
using AutoMail.Service.Interface;
using Quartz.Logging;
using AutoMail.Log.QuartzLog;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<AutoMailContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("AutoMailContext") ?? throw new InvalidOperationException("Connection string 'AutoMailContext' not found.")));

// Add services to the container.
builder.Services.AddControllersWithViews();


// Add Quartz services
LogProvider.SetCurrentLogProvider(new QuartzLogProvider());
builder.Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();
builder.Services.AddSingleton<IQuartzService, QuartzService>();
builder.Services.AddScoped<IJobsManager, JobsManager>();

// Add our job
builder.Services.AddSingleton<BirthdayMailSendJob>();
builder.Services.AddSingleton<AnniversaryMailSendJob>();

// Host Quartz Service
builder.Services.AddHostedService<QuartzService>();

// Add logger
builder.Logging.AddProvider(new MyLoggerProvider(builder.Configuration));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=EmailJobs}/{action=Index}/{id?}");

var services = app.Services.CreateScope().ServiceProvider;
var quartzService = services.GetRequiredService<IQuartzService>();
var jobsManager = services.GetRequiredService<IJobsManager>();

var currentStaffsMailJobs = await jobsManager.CurrentStaffsMailJobs();
if (currentStaffsMailJobs != null)
{
    await quartzService.SchedulingJobs(currentStaffsMailJobs); 
}

app.Run();
